const ws = require("nodejs-websocket");
const moment = require('moment');
const serverConfig = {
    port: 8206,
    host: "localhost",
}
console.log("开始建立连接...", serverConfig.port);
let users = [];
let msgList = [];

// 向连接的客户端广播
function boardcast(obj) {
    server.connections.forEach(function(conn) {
        conn.sendText(JSON.stringify(obj));
    })
}

function getDate() {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}

var server = ws.createServer(function(conn) {
    conn.on("text", function(obj) {
        obj = JSON.parse(obj);
        if (obj.type === "heart") {
            console.log('heartbeat', obj.uid, new Date())
        } else if (obj.type === "chat") {
            console.log("oo-->", obj);
            // let {fromUid,toUid } = obj;
            // obj.fromUid = toUid;
            // obj.toUid = fromUid;
            let target = msgList.find(it => it.mid == obj.mid)
            if(!target){
                msgList.push(obj);
                boardcast(obj);
            }
        } else {
            console.log(obj)
            boardcast({
                type: "letter",
                date: getDate(),
                msg: obj.msg,
                uid: obj.uid,
                nickname: obj.nickname,
                fromPhonenum: obj.fromPhonenum,
                toPhonenum: obj.toPhonenum,
            });
        }
    })
    conn.on("close", function(code, reason) {
        console.log("关闭连接",code,reason)
    });
    conn.on("error", function(code, reason) {
        console.log("异常关闭",code, reason)
    });
}).listen(serverConfig.port, serverConfig.host, () => {
    console.log("WebSocket建立完毕...");
    console.log("http://" + serverConfig.host + ":" + serverConfig.port);
});